import axios from "axios";
import store from "../store";

let http = axios.create({
  baseURL: "http://shop.bluej.cn/api",
  timeout: 8000,
});

http.interceptors.request.use((config) => {
  let token = store.state.user.token;
  if (token) {
    config.headers["x-token"] = token;
  }
  return config;
});

// 登录
export function post(url, data) {
  return new Promise((resolve, reject) => {
    http
      .post(url, data, {
        headers: {
          "Content-Type": "application/json",
        },
      })
      .then(
        (res) => {
          resolve(res);
        },
        (err) => {
          console.log("错误");
          reject(err);
        }
      );
  });
}

// 带token的post
export function postToken(url, data) {
  return new Promise((resolve, reject) => {
    http
      .post(url, data, {
        headers: {
          "Content-Type": "application/json",
        },
      })
      .then(
        (res) => {
          console.log(res);
          resolve(res);
        },
        (err) => {
          console.log(token);
          console.log("错误");
          reject(err);
        }
      );
  });
}

// axios 提供了一个能力
// params可以自动帮我们把参数拼接到url上
// {a:1,b:2} 直接传递即可
export const get = (url, params = {}) => {
  return new Promise((resolve, reject) => {
    http.get(url, { params }).then(
      (res) => {
        resolve(res.data);
        console.log(res);
      },
      (err) => {
        reject(err);
      }
    );
  });
};

// 带token的get
export const getget = (url, token) => {
  return new Promise((resolve, reject) => {
    http
      .get(url, {
        headers: {
          "Content-Type": "application/json",
        },
      })
      .then(
        (res) => {
          resolve(res.data);
          console.log(res);
        },
        (err) => {
          reject(err);
        }
      );
  });
};

// 购物车改变后台商品数量
export function put(url, data) {
  return new Promise((resolve, reject) => {
    http.put(url, data).then(
      (res) => {
        console.log(res);
        resolve(res);
      },
      (err) => {
        console.log(token);
        console.log("错误");
        reject(err);
      }
    );
  });
}

// 删除商品
export function delNum(url, data) {
  return new Promise((resolve, reject) => {
    http.delete(url, data).then(
      (res) => {
        console.log(res);
        resolve(res);
      },
      (err) => {
        // console.log(token);
        console.log("错误");
        reject(err);
      }
    );
  });
}
